package com.darren.euc.dao.impl;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.darren.euc.dao.ContractProductDao;
import com.darren.euc.entity.ContractProduct;


@Repository
public class ContractProductDaoImpl extends BaseDaoImpl<ContractProduct, Integer> implements ContractProductDao {
	
	@Override
	public List<ContractProduct> getAll() {
		Session session = sessionFactory.getCurrentSession();	
		@SuppressWarnings("unchecked")
		List<ContractProduct> contractProducts = session.createQuery("from ContractProduct where enable = true").list();
		return contractProducts;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ContractProduct> queryContractProducts(Integer spaceId,String roomName,String rentStart,String rentEnd){		
		Session session = sessionFactory.getCurrentSession();	
		String SQL = "SELECT * FROM euc_contract_product product WHERE	product.space_id = ? and product.room_name like ? AND (?  BETWEEN product.rent_start  AND product.rent_end	OR ? BETWEEN product.rent_start  AND product.rent_end OR product.rent_start BETWEEN ?  AND ?  OR product.rent_end BETWEEN ?  AND ?);";
		Query query = session.createSQLQuery(SQL).addEntity(ContractProduct.class);
		query.setInteger(0, spaceId);
		query.setString(1, "%"+roomName+"%");
		query.setString(2,rentStart);
		query.setString(3,rentEnd);
		query.setString(4,rentStart);
		query.setString(5,rentEnd);
		query.setString(6,rentStart);
		query.setString(7,rentEnd);
		return query.list();
	}

	@Override
	public List<ContractProduct> queryByContractId(Integer contractId) {
		Session session = sessionFactory.getCurrentSession();	
		String SQL = "SELECT * FROM euc_contract_product WHERE	contract_id  = ?;";
		Query query = session.createSQLQuery(SQL).addEntity(ContractProduct.class);
		query.setInteger(0, contractId);
		return query.list();
	}

	@Override
	public void deleteByContractId(Integer contractId) {
		Session session = sessionFactory.getCurrentSession();	
		String SQL = "delete FROM euc_contract_product WHERE	contract_id  = ?;";
		Query query = session.createSQLQuery(SQL);
		query.setInteger(0, contractId);
		query.executeUpdate();		
	}

	@Override
	public List<ContractProduct> findByRoomId(Integer roomId) {
		Session session = sessionFactory.getCurrentSession();
		String SQL = "SELECT * FROM euc_contract_product WHERE	room_id  = ?;";
		Query query = session.createSQLQuery(SQL).addEntity(ContractProduct.class);
		query.setInteger(0, roomId);
		return query.list();
	}

}